## Author: 	M. Orlowski
## Project:	Coalition Probabilities
## Content:	Function to predict from survival::clogit

predCL <- function(mod, new.dat = NULL, type = "expected", strat.var = "case"){
	##
	## This function computes the linear predictors or conditional predicted 
	## probabilities for a given mconditional logit fit 
	##
	## Args.:
	##	mod:		A clogit model object
	## 	new.dat: 	A data frame for which predictions should be made
	## 	type: 		A character value in c('lp', 'expected') indicating the type 
	## 				of prediciton. Default is 'expected'.
	## 	strat.var:	An integer or character value indicating the column identifying
	## 				the strata. Default is "case"
	##
	## Returns:
	##	A numeric vector with predictions
	##
	
	require(plyr)

	if(is.null(new.dat)){

		out <- predict(mod, type = type)
	
	}else{

		tmp_id <- 1:nrow(new.dat)

		coefs <- coefficients(mod)

		# Error handling
		if( !strat.var %in% names(new.dat) ){

			stop("Provide a valid stratification variable")

		}

		if( !all(names(coefs) %in% names(new.dat)) ){

			stop("Not all covariates in prediction data")

		}
		
		if( !is.character(type) || ! type %in% c("lp", "expected") ){

			stop("Invalid type")
		}
		
		tmp <- new.dat[, which(names(new.dat) %in% c(names(coefs), strat.var, "tmp_id"))]
		mdat <- tmp[, match(names(coefs), names(tmp))]
		
		# Deal with single variable models
		if( is.null(dim(mdat)) ){

			mdat <- as.data.frame(mdat)
			names(mdat) <- names(coefs)

		}
		mdat[[strat.var]] <- tmp[[strat.var]]

		# linear predictors
		mdat$lp <- as.matrix(mdat[, -which(names(mdat) == strat.var)]) %*% coefs

		if(type == "lp"){

			out <- mdat$lp

		}else if(type == "expected"){

			# expected probabilities
			tmp <- ddply(cbind(mdat, tmp_id), as.quoted(strat.var), function(dat){
					dat[["pr"]] <- exp(dat[["lp"]])/sum(exp(dat[["lp"]]))
					dat	
				})
			tmp <- tmp[order(tmp$tmp_id),]
			out <- tmp$pr
			
		}

	}
	
	return(out)
}
